package com.disk.service.impl;

import com.disk.domain.FileDetail;
import com.disk.domain.FileInformation;
import com.disk.handleResult.DiskMessage;
import com.disk.handleResult.FileResult;
import com.disk.handleResult.ReturnStatus;
import com.disk.service.FileService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.List;
import java.util.Objects;

@Service
@Data
public class FileServiceImpl implements FileService {
    @Value(value = "${file.root.dir}")
    private String rootDir;

    private String root=rootDir;

    private FileInputStream fis = null;
    private BufferedInputStream bis = null;


    public void setUserRoot(String username){
        File rootFolder = new File(rootDir);
        if(!rootFolder.exists())
        {
            rootFolder.mkdir();
        }
        if (username.isEmpty())
        {
            setRoot(rootDir);
        }
        else {
            String result = rootDir+username+File.separator;
            setRoot(result);
            File newFolder = new File(rootDir, username);
            if(!newFolder.exists())
            {
                newFolder.mkdir();
            }
        }
    }

    /**
     * 向系统增加文件(上传)
     *
     * @param folderName 上传目标子文件夹
     * @param file       上传的文件
     */
    public FileResult upload(String folderName,MultipartFile file) {

        FileResult fileResult = new FileResult();
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        try {

            //File.separator == ""+separatorChar 用 File.separator 保证了在任何系统下不会出错:Windows/Linux
            File dest = new File(root, folderName + File.separator + fileName);
            //当文件父文件夹不存在，则创建该文件夹
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdir();
            }
            file.transferTo(dest);
            fileResult.setStatus(ReturnStatus.SUCCESS);
            fileResult.setMessage(DiskMessage.UPLOAD_SUCCESS);
            fileResult.setFolderName(folderName);
            fileResult.setFileName(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            fileResult.setStatus(ReturnStatus.FAIL);
            fileResult.setMessage(e.getMessage());
            fileResult.setFolderName(folderName);
            fileResult.setFileName(fileName);
        }
        return fileResult;
    }

    /**
     * 批量向系统增加文件(上传)
     *
     * @param folderName 上传目标子文件夹
     * @param files      上传的文件们，调用API时，form-data中可传多个file名字的文件
     */
    public FileResult uploadFiles(String folderName, List<MultipartFile> files) {

        FileResult fileResult = new FileResult();

        StringBuilder responseFileName = new StringBuilder();
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            assert fileName != null;
            responseFileName.append(fileName).append(";");
            try {
                File dest = new File(root, folderName + File.separator + fileName);
                //当文件父文件夹不存在，则创建该文件夹
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdir();
                }

                file.transferTo(dest);
            } catch (Exception e) {
                e.printStackTrace();
                fileResult.setStatus(ReturnStatus.FAIL);
                fileResult.setMessage(e.getMessage());
                fileResult.setFolderName(folderName);
                fileResult.setFileName(responseFileName.toString());
            }
            fileResult.setStatus(ReturnStatus.SUCCESS);
            fileResult.setMessage(DiskMessage.UPLOAD_SUCCESS);
            fileResult.setFolderName(folderName);
            fileResult.setFileName(responseFileName.toString());
        }

        return fileResult;
    }

    /**
     * 删除系统中的文件
     *
     * @param folderName 要删除的文件的目标文件夹
     * @param fileName   要删除的文件
     */
    public FileResult delete( String folderName,  String fileName) {


        FileResult fileResult = new FileResult();
        File file = new File(root, folderName + "\\" + fileName);
        try {
            if (file.exists()) {
                file.delete();

                fileResult.setStatus(ReturnStatus.SUCCESS);
                fileResult.setMessage(DiskMessage.DELETE_SUCCESS);
                fileResult.setFolderName(folderName);
                fileResult.setFileName(fileName);
                return fileResult;
            }
            fileResult.setStatus(ReturnStatus.FAIL);
            fileResult.setMessage(DiskMessage.ASK_FILE_FAIL);
            fileResult.setFileName(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            fileResult.setStatus(ReturnStatus.FAIL);
            fileResult.setMessage(e.getMessage());
            fileResult.setFolderName(folderName);
            fileResult.setFileName(fileName);
        }
        return fileResult;
    }

    /**
     * 批量删除系统中的文件
     *
     * @param files 要删除的文件
     */
    public FileResult deleteFiles(FileDetail[] files) {

        FileResult fileResult = new FileResult();
        if (files.length == 0) {
            fileResult.setStatus(ReturnStatus.FAIL);
            fileResult.setMessage("请选择要删除的文件");
            return fileResult;
        }

        int successQuantity = 0;
        int failQuantity = 0;
        FileDetail file1 = files[0];
        String folderName = file1.getPath();
        for (int i = 0; i < files.length; i++) {
            FileDetail fileDetail = files[i];
            String fileName = fileDetail.getName();
            File file = new File(root, folderName + "\\" + fileName);
            try {
                if (file.exists()) {
                    file.delete();
                    successQuantity += 1;
                    continue;
                }
                failQuantity += 1;
            } catch (Exception e) {
                e.printStackTrace();
                failQuantity += 1;
            }
        }
        if (failQuantity == 0 && successQuantity > 0) {
            fileResult.setStatus(ReturnStatus.SUCCESS);
            fileResult.setMessage(DiskMessage.DELETE_SUCCESS);
            fileResult.setFolderName(folderName);
        }
        if (failQuantity > 0) {
            fileResult.setStatus(ReturnStatus.FAIL);
            fileResult.setMessage("删除成功：" + successQuantity + ",删除失败：" + failQuantity);
            fileResult.setFolderName(folderName);
        }
        return fileResult;
    }

    /**
     * 修改系统中的文件名
     *
     * @param fileInformation 文件信息
     */
    public FileResult updateFile( FileInformation fileInformation) {

        FileResult fileResult = new FileResult();
        String folder = root + "\\" + fileInformation.getFolderName();
        String currentFileName = fileInformation.getCurrentFileName();
        String targetFileName = fileInformation.getTargetFileName();

        File currentFile = new File(folder, currentFileName);
        File targetFile = new File(folder, targetFileName);
        try {
            if (targetFile.exists()) {
                fileResult.setStatus(ReturnStatus.FAIL);
                fileResult.setMessage(DiskMessage.REPEAT_FILE);
                fileResult.setFileName(targetFileName);
                return fileResult;
            }
            if (currentFile.exists()) {
                currentFile.renameTo(targetFile);

                fileResult.setStatus(ReturnStatus.SUCCESS);
                fileResult.setMessage(DiskMessage.UPDATE_SUCCESS);
                fileResult.setFileName(targetFileName);
                return fileResult;
            }
            fileResult.setStatus(ReturnStatus.FAIL);
            fileResult.setMessage(DiskMessage.ASK_FILE_FAIL);
            fileResult.setFileName(currentFileName);
        } catch (Exception e) {
            e.printStackTrace();
            fileResult.setStatus(ReturnStatus.FAIL);
            fileResult.setMessage(e.getMessage());
            fileResult.setFileName(currentFileName);
        }
        return fileResult;
    }

    /**
     * 下载系统中的文件
     *
     * @param folderName 被下载的目标子文件夹
     * @param fileName   被下载的文件
     */
    public FileResult tryDown(String folderName,String fileName){

        String folder = root + "\\" + folderName;
        File file = new File(folder, fileName);
        FileResult fileResult = new FileResult();

        try {
            HttpServletResponse response = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            FileCopyUtils.copy(Files.newInputStream(file.toPath()), response.getOutputStream());
            fileResult.setStatus(ReturnStatus.SUCCESS);
            fileResult.setMessage(DiskMessage.DOWN_SUCCESS);
            fileResult.setFolderName(folderName);
            fileResult.setFileName(fileName);
        } catch (IOException e) {
            e.printStackTrace();
            fileResult.setStatus(ReturnStatus.FAIL);
            fileResult.setMessage(e.getMessage());
            fileResult.setFolderName(folderName);
            fileResult.setFileName(fileName);
        }
        return fileResult;
    }
}
